<template>
  <div >
    <!--    第一项 搜索框和重置按钮-->
    <div class="card">
      <el-input v-model="data.searchTitle" placeholder="请输入文章标题" style="width: 200px;margin-right: 5px;" suffix-icon="Search"/>
      <el-button type="primary" @click="loadData()">搜索</el-button>
      <el-button type="warning" @click="reset()">重置</el-button>
    </div>

    <!--    第二项 常用操作 批量删除 添加文章-->
    <div class="card">
      <el-button type="primary" @click="switchAddDialog">新建文章</el-button>
      <el-button type="danger" @click="deleteBatchMessageBox">批量删除</el-button>
    </div>

    <!--    第三项 文章数据表格-->
    <div class="card">
      <el-table @selectionChange="handleSelectionChange" :data = "data.tableData" height="400" style="width: 100%;border: #7a7575 solid 1px">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号" />
        <el-table-column prop="title" label="文章标题" />
        <el-table-column prop="" label="封面" >
          <template #default="scope">
            <el-image v-if="scope.row.img" :preview-teleported="true" :preview-src-list=[scope.row.img] :src="scope.row.img" alt="" style="width: 100px;height:  60px;"/>
          </template>

        </el-table-column>
        <el-table-column prop="description" label="简介" show-overflow-tooltip />

        <el-table-column prop="time" label="发布时间" />
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button  type="primary" @click="read(scope.row)" circle>
              <el-icon><View /></el-icon>
            </el-button>
            <el-button  type="warning"  @click="editRow(scope.row)" circle>
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button  type="danger" @click="deleteMessageBox(scope.row)" circle>
              <el-icon><Delete /></el-icon>
            </el-button>

          </template>
        </el-table-column>

      </el-table>
    </div>

    <!--    第四项 分页组件-->
    <div class="card">
      <el-pagination

          v-model:current-page="data.currentPage"
          v-model:page-size="data.pageSize"
          @current-change="loadData"
          @size-change="loadData"
          :page-sizes="[10, 20, 50, 100]"

          layout="total, sizes, prev, pager, next, jumper"
          v-model:total="data.total"

      />
    </div>
    <!--    第五项 添加和修改文章对话框-->
    <el-dialog
        v-model="data.AddDialogVisible"
        title="新建文章"
        width="800"
        destroy-on-close
    >
      <el-form   :model="data.article" style="padding-right: 40px;padding-top: 20px" >
        <el-form-item label="标题" prop="title">
          <el-input :disabled="data.article.id != 0" v-model="data.article.title" autocomplete="off" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
              :action="$baseUrl + '/files/upload'" list-type="picture"
            :on-success="handleAvatarSuccess"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>

        </el-form-item>

        <el-form-item label="简介" prop="description">
          <el-input type="textarea" :rows="3" v-model="data.article.description" autocomplete="off"  placeholder="请输入简介"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content" >

          <div  style="border:1px solid #ccc; width: 100%" >
            <Toolbar
                style="border-bottom:1px solid #ccc"
                :editor="editorRef"
                :mode="mode"
            />
            <Editor
                style="height:  500px; overflow-y:hidden;"
                v-model="data.article.content"
                :mode="mode"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
            />

          </div>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="switchAddDialog">取消</el-button>
          <el-button type="primary" @click="save()">
            确定
          </el-button>
        </div>
      </template>


    </el-dialog>
    <!-- 阅读文章对话框 -->
    <<el-dialog
      v-model="data.viewVisible"
      title="阅读文章"
      width="70%"
      :destroy-on-close="true"
  >
    <div style="padding: 20px; background-color: #f9f9f9; border-radius: 8px;">
      <h2 style="color: #333;">{{ data.article.title }}</h2>
      <p style="color: #666; font-size: 14px;">发布时间：{{ data.article.time }}</p>
      <div style="margin-top: 20px; color: #555; line-height: 1.6;" v-html="data.article.content"></div>

      <div style="margin-top: 20px; display: flex; align-items: center;">
        <el-button @click="toggleLike" :type="data.isLiked ? 'danger' : 'default'" circle>
          <el-icon :size="20">
            <StarFilled v-if="data.isLiked" />
            <Star v-else />
          </el-icon>
        </el-button>
        <span style="margin-left: 8px; color: #666; font-size: 14px;">{{ data.likeCount }} 人喜欢</span>
      </div>

    </div>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="data.viewVisible = false">关闭</el-button>
    </span>
    </template>
  </el-dialog>
  </div>
</template>
<script setup>


import request from "@/utils/request.js";
import {ElMessage,ElMessageBox} from "element-plus";
import '@wangeditor/editor/dist/css/style.css' //引入 css
import {reactive,onBeforeUnmount,ref,shallowRef} from "vue";
import {Editor,Toolbar } from '@wangeditor/editor-for-vue'
import { Star, StarFilled } from '@element-plus/icons-vue'

const res = ref();
const data =  reactive({
  AddDialogVisible:false,
  tableData: [
  ],
  currentPage:1,
  pageSize:5,
  searchTitle:'',
  article:{
    id:0,
    content:'',
  },
  ids:[],
  rules:{
    title:[
      {required:true,message:'请输入标题',trigger:'blur'},
      {min:3,max:10,message:'长度在3到10个字符',trigger:'blur'}
    ],
    password:[
      {required:true,message:'请输入密码',trigger:'blur'},
      {min:3,max:10,message:'长度在3到10个字符',trigger:'blur'}
    ],
    viewVisible: false,
    isLiked: false, // <-- 2. 新增状态
    likeCount: 0,   // <-- 2. 新增状态

  },
  user: JSON.parse(localStorage.getItem("zwy-user")) || {} // <-- 2. 获取用户信息
})

/*wangEditor5初始化开始*/
const baseUrl = request.defaults.baseURL; // 改为这一行
const editorRef = shallowRef() //编辑器实例，必须用 shallowRef
const mode = 'default'
const editorConfig = {MENU_CONF: {}}
//图片上传配置
editorConfig.MENU_CONF['uploadImage']= {
  server: `${baseUrl}/files/wang/upload`,//服务端图片上传接口
  fieldName:'file',//服务端图片上传接口参数
  base64LimitSize: 2 * 1024 * 1024, // 可选：小于该值才使用 base64 插入（单位：字节）
  // 自定义插入回传的图片 URL（可选）
  customInsert(res, insertFn) {
    // 假设后端返回格式是 { url: 'http://localhost:9999/files/download/xxx.png' }
    insertFn(res.url)
  },
  // 自定义上传前处理（可选）
  customUpload(file, insertFn, failFn) {
    const formData = new FormData()
    formData.append('file', file)

    fetch(`${baseUrl}/files/upload`, {
      method: 'POST',
      body: formData
    })
        .then(response => response.json())
        .then(result => {
          if (result.code === '200') {
            insertFn(result.data) // 调用插入函数
          } else {
            failFn('上传失败')
          }
        })
        .catch(() => {
          failFn('网络错误')
        })
  }

}
//组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
// 记录 editor 实例，重要！
  const handleCreated = (editor) => {
    editorRef.value = editor
  }

  /*wangEditor5 初始化结束*/

const view = (content) => {
  data.content = content
  data.vieVisible = true
}
const loadData = () => {


  const loadAll = () =>{

    request.get('article/selectPage', {
      params: {
        pageNum: data.currentPage,
        pageSize: data.pageSize,
      }
    }).then(res=> {
      data.tableData = res.data.list;
      data.total = res.data.total;

      console.log(res.data.list)
    })
  }
  const loadByTitle = () =>{
    request.post('article/findByTitle',{
      title:data.searchTitle,
    },{  params: {
        pageNum: data.currentPage,
        pageSize: data.pageSize,
      }}).then(res=>{
      data.tableData = res.data.list;
      data.total = res.data.total;
      console.log(res.data.list)
    })
  }
  data.searchTitle ? loadByTitle() :loadAll()
}
loadData();
const reset = () =>{
  data.searchTitle = '';
  loadData();
}

const switchAddDialog = () =>{
  data.article =  {
    id:0,
    title:'',
    description:'',
    content:'',
    img:'',
  }
  data.AddDialogVisible = data.AddDialogVisible ? false : true;
}
const read = (row) =>{ // <-- 3. 修改 read 方法
  request.get('article/findById/' + row.id).then(res=>{
    data.article = res.data;
    loadLikeData(row.id); // <-- 调用加载点赞数据的方法
  })
  data.content = row.content;
  data.viewVisible = true;
}

// 4.修改 loadLikeData 方法
const loadLikeData = (articleId) => {
  if (!data.user || !data.user.username || !data.user.role) return;
  // 构造唯一标识符，例如: "ADMIN-zwy" 或 "EMP-tom"
  const userIdentifier = `${data.user.role}-${data.user.username}`;

  request.get(`/article/like/count/${articleId}`).then(res => {
    data.likeCount = res.data;
  });
  // 调用新的接口
  request.get(`/article/isLiked/${articleId}/${userIdentifier}`).then(res => {
    data.isLiked = res.data;
  });
}

//5. 修改 toggleLike 方法
const toggleLike = () => {
  console.log(data)
  if (!data.user || !data.user.username || !data.user.role) {
    ElMessage.error('请先登录再进行操作');
    return;
  }
  const articleId = data.article.id;
  const userIdentifier = `${data.user.role}-${data.user.username}`;

  if (data.isLiked) {
    // 调用新的接口
    request.delete(`/article/unlike/${articleId}/${userIdentifier}`).then(() => {
      data.isLiked = false;
      data.likeCount--;
    });
  } else {
    // 调用新的接口
    request.post(`/article/like/${articleId}/${userIdentifier}`).then(() => {
      data.isLiked = true;
      data.likeCount++;
    });
  }
}

const editRow = (row) =>{
  request.get('article/findById/' + row.id).then(res=>{
    data.article = res.data;
  })
  switchAddDialog();
  //深拷贝,解决就算取消修改，数据还是被修改了的问题
  data.article = JSON.parse(JSON.stringify(row));

}
const save = () =>{

      data.article.id != 0 ? update() : add();



}
const update = () =>{
  request.put('article/modify',data.article).then(res=>{
    console.log(res);
    if(res.code === '200'){
      ElMessage.success('添加成功');
      loadData();
      switchAddDialog();
    }else {
      ElMessage.error(res.code + '/n' + res.msg);
    }
  })
}
const add = () =>{
  request.post('article/add',data.article).then(res=>{
    console.log(res);
    if(res.code === '200'){
      ElMessage.success('添加成功');
      loadData();
      switchAddDialog();
    }else {
      ElMessage.error(res.code + '/n' + res.msg);
    }
  })
}
const deleteOne = (row) =>{
  request.delete(`article/deleteById/${row.id}`).then(res=>{
    if(res.code === '200'){
      ElMessage.success('删除成功');
      loadData();
    }else {
      ElMessage.error(res.code + '/n' + res.msg);
    }
  })
}
const handleSelectionChange = (rows) =>{
  data.ids = rows.map(row => row.id);
  console.log(data.ids);
}
const deleteBatch = () =>{
  request.delete(`article/deleteBatch`,{data:data.ids}).then(res=>{
    if(res.code === '200'){
      ElMessage.success('批量删除成功');
      loadData();
    }else {
      ElMessage.error(res.code + '/n' + res.msg);
    }

  })
}
const deleteMessageBox = (row) =>{
  ElMessageBox.confirm('此操作将永久删除该信息, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'danger',
  }).then(() => {
    deleteOne(row);
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    });
  });
}
const deleteBatchMessageBox = () =>{
  if(data.ids.length === 0){
    ElMessage.error('请选择要删除的数据');
    return;
  }
  ElMessageBox.confirm('此操作将永久删除该信息, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'danger',
  }).then(() => {
    deleteBatch();
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    });
  });
}
const handleAvatarSuccess = (res) =>{
  data.article.img = res.data.url;
}
</script>
